/*
 * @(#)ExecOfflineSql.java   1.0  2021年11月17日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.offline.exec;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.swift.dao.db.datasource.HandlerDataSource;
import com.swift.dao.db.springjdbc.Jdbc;
import com.swift.dts.dao.OfflineSqlTableDao;
import com.swift.dts.dao.model.OfflineSqlTable;
import com.swift.dts.dao.model.SynObjectKey;
import com.swift.util.type.TypeUtil;

/**
 * 添加说明
 * 
 * @author zhengjiajin
 * @version 1.0 2021年11月17日
 */
@Component
public class ExecOfflineSql {

    // private static final Logger log = LoggerFactory.getLogger(ExecOfflineSql.class);
    @Autowired
    private Jdbc jdbc;

    @Autowired
    private OfflineSqlTableDao offlineSqlTableDao;

    public void cleanOfflineSql(SynObjectKey key) {
        offlineSqlTableDao.delete(key);
    }
    
    public void execOfflineSql(SynObjectKey key) {
        synchronized (key.getDataSource().intern()) {
            List<OfflineSqlTable> sqlList = offlineSqlTableDao.list(key);
            HandlerDataSource.putDataSource(key.getDataSource());
            while(TypeUtil.isNotNull(sqlList)) {
                execSql(key, sqlList);
                sqlList = offlineSqlTableDao.list(key);
            }
            HandlerDataSource.clear();
        }
    }
 
    private void execSql(SynObjectKey key, List<OfflineSqlTable> sqlList) {
        if (TypeUtil.isNull(sqlList)) return;
        for (OfflineSqlTable sql : sqlList) {
            try {
                HandlerDataSource.putDataSource(key.getDestination());
                offlineSqlTableDao.delete(sql.getSqlId());
                jdbc.execute(sql.getSqlStr());
                HandlerDataSource.clear();
            } catch (Exception ex) {
            }
        }
    }
}
